<?php

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\SystemBusiness;
use app\model\SystemBusinessCommissionRatio;
use app\model\SystemCertificate;
use app\model\SystemOperateLog;
use app\model\User;
use app\Request;
use app\service\Certificate;
use app\service\FinanceServer;
use app\service\System;
use app\stateData;
use app\validate\Business;
use PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use app\model\SystemBusiness as BusinessModel;

class SystemCertificateBusiness extends BaseController
{
/**
 * 证书管理 业务管理控制器
 */

    private $operate_Log;//日志model

    private $certificate;//证书类

    private $business; //业务类



    public function __construct(App $app,SystemOperateLog $operate_Log,SystemCertificate $certificate,BusinessModel $business)
    {
        parent::__construct($app);

        $this->operate_Log = $operate_Log;

        $this->certificate = $certificate;

        $this->business = $business;


    }

    //获取证书管理列表
    public function getCertificateList(Request $request,System $systemService)
    {
        $page = $request->get('page')?:0;
        $pageNum = $request->get('pageNum')?:stateData::$_page;

        $list = $this->certificate->getCertificateListModel()->toArray();

        if (!empty($list)){

            $tree_list = $systemService->menuTreeList($list,0,1);
        }else{
            $tree_list = [];
        }

        $pages['total'] = $this->certificate->getCertificateCountModel();
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$tree_list,$pages);
    }

    /**
     * 新增 获取全部等级证书tree
     * @param \app\Request $request
     * @param \app\service\System $systemService
     * @return false|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCertificateAllList(Request $request,System $systemService)
    {
        $page = $request->get('page')?:0;
        $pageNum = $request->get('pageNum')?:stateData::$_page;

        $list = $this->certificate->getCertificateListModel()->toArray();

        if (!empty($list)){

            $tree_list = $systemService->menuTreeList($list,0);
        }else{
            $tree_list = [];
        }

        $pages['total'] = $this->certificate->getCertificateCountModel();
        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$tree_list,$pages);
    }


    //获取证书等级下面的全部专业
    public function getLevelToSpeciality(Request $request,Certificate $certificate,FinanceServer $financeServer)
    {
        $page = $request->get('page')?:0;
        $pageNum = $request->get('pageNum')?:stateData::$_page;

        $id = $request->get ('pid');

        $where = $request->get ('where')?:'';

        if (!isset($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $data = $certificate->setCertificateZhuanye ($id,$where);
        $pages['pageNumber'] = $pageNum;
        $pages['total'] = count($data);
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,page($data,$page,$pageNum),$pages);
    }

    //删除证书
    public function delCertificates(Request $request,SystemOperateLog $log)
    {
        /**
         * 接收参数
         * @param $id
         */
        $id = $request->post('id');

        if (empty($id)) return ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //判断该id是否有子类，如果有 不允许删除
        $subClass = $this->certificate->getIdSubClass($id);

        if (!empty($subClass)) return ReJson(message::$ERROR_CODE,message::$ERR_SUB_CLASS);

        $result = $this->certificate->delCertificateModel([$id]);

        if ($result){

            $log->addOperate($request->param ('user_login_id'),message::$CERTIFICATE,message::$SUCC_SYSTEM_DELETE_CERTIFICATE);

            return ReJson(message::$SUCC_CODE,message::$SUCC_DATELE_DATA);
        }

        return ReJson(message::$ERROR_CODE,message::$ERR_DATELE_DATA);


    }


    /*新增证书
     * 暂定弃用
     * $this->addCertificate()
     */
    public function deprecatedAddCertificate(Request $request)
    {
        /**
         * 接收参数
         * @param $certificate_name
         * @param $certificate_type
         * @param $parent_id
         */
        $param = $request->post();

        try {

            Validate(\app\validate\Certificate::class)->check($param);

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        //判断数据库是否存在本条内容，存在的话返回id 不存在添加返回id
        // 继续查找下一级同上递归
        $count = count($param);

        $data = array_values($param);

        $pid = 0;
        for ($i = 0; $i < $count; $i++) {

            if ($i == 0) continue;

            //查询父类类别证书是否存在
            $pid = $this->certificate->getCertificateIdModel($data[$i-1],$i-1,$pid);

            if (!is_int($pid)) $pid = 0;

            //查询当前类别证书是否存在
            $id = $this->certificate->getCertificateIdModel($data[$i],$i,$pid);

            //存在不处理,添加当前类别证书父类pid
            if (empty($id)){
                $this->certificate->getCertificateIdModel($data[$i],$i,$pid);
            }
        }
        return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA);

    }

    //新增证书
    public function addCertificate(Request $request,SystemOperateLog $log)
    {
        /**
         * 接收参数
         * @param $certificate_name
         * @param $certificate_type
         * @param $parent_id
         */
        $param = $request->post();
        Log::error ($param);
        try {
//            Validate(\app\validate\Certificate::class)->check($param);
           $result = $this->certificate->addCertificateModel(
                $param['certificate_name'],
                $param['certificate_type'],
                $param['parent_id']
            );

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
        }
        $log->addOperate($request->param ('user_login_id'),message::$CERTIFICATE,message::$SUCC_SYSTEM_ADD_CERTIFICATE);

        return ReJson(message::$ERROR_CODE,message::$ERR_INSERT_DATA);

    }

    //修改证书

    public function editCertificates(Request $request,SystemOperateLog $log)
    {
        /**
         * 接收参数
         * @param $certificate_name
         * @param $id
         */
        $param = $request->post();
//        Log::error ($param);
        try {
            Validate(\app\validate\Certificate::class)->scene("edit")->check($param);


            $result = $this->certificate->editCertificateModel($param);
        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE);
        }
        $log->addOperate($request->param ('user_login_id'),message::$CERTIFICATE,message::$SUCC_SYSTEM_UPDATE_CERTIFICATE);

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //是否启用证书
    public function eDCertificate(Request $request,SystemOperateLog $log)
    {
        /**
         * 接收参数
         * @param $id
         * @param $is_k
         */
        $param = $request->post();
        try {

            Validate(\app\validate\Certificate::class)->scene("isDe")->check($param);

            $result = $this->certificate->editCertificateModel($param);
        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE);
        }
        $log->addOperate($request->param ('user_login_id'),message::$CERTIFICATE,message::$SUCC_SYSTEM_CERTIFICATE_STATUS_DE);

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);

    }



    /***************************************业务管理**********************************************/

    //查询业务大分类
    public function getTypeList()
    {
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,stateData::$_business_type);
    }

     //查询负责人列表
    public function getUserList(User $userModel)
    {

        $userData = $userModel->getUserNameList();

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$userData);
    }


    //查看业务列表
    public function getBusinessList(
        Request $request,
        System $systemService,
        User $userModel,
        SystemBusinessCommissionRatio $systemBusinessCommissionRatioModel
    ){
        $page = $request->get('page')?:1;
        $pageNum = $request->get('pageNum')?:stateData::$_page;
        $business_name = $request->get ('business_name')?:'';

        $result = $this->business->getBusinessListModel($business_name,$pageNum,$page);
        //针对批量负责人id处理
        $headId = array();
        $userName = "";
        foreach ($result as $key => $item) {

            $headId = $systemService->analysisId($item['head_id']);

            foreach ($headId as $items) {

                if(!empty($userName)){
                    $userName .= ",".$userModel->getIdNickName($items);
                }else{
                    $userName .= $userModel->getIdNickName($items);
                }
            }
            //获取业务对应提成比例
            $result[$key]['commission_ratio'] = $systemBusinessCommissionRatioModel->getBidDataModel($item['id']);
            $result[$key]['head_name'] = $userName;
            $userName = '';
        }

        $pages['total'] = $this->business->getPageTotal ($business_name); //获取总条数

        $pages['pageNumber'] = $pageNum; //每页显示多少条

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result,$pages);
    }

    //添加业务
    public function addBusiness(Request $request,SystemOperateLog $log,SystemBusinessCommissionRatio $businessCommissionRatioModel)
    {
        /**
         * @param $business_name
         * @param $business_type
         * @param $head_id string
         */
        $param = $request->post();

        Db::startTrans();
        try {
//            Validate(Business::class)->check($param);

            //是否有设置提成比列
            if (isset($param['commission_ratio']) & is_array ($param['commission_ratio'])){
                $commissionArr = $param['commission_ratio'];

                //添加业务
                $result = $this->business->addBusinessModel($param);
                //提成比例入库
                foreach ($commissionArr as $item) {
                    //判断是否满足入库规则
                    if (!empty($item['field']) || !empty($item['field2'])){
                        if ($item['field'] >= $item['field2']){
//                            $this->business->delBusinessModel (['id'=>$result->id]);
                            return ReJson (message::$ERROR_CODE,message::$ERR_CHECK_COMMISSION_RATIO_BETWEEN);
                        }
                    }

                    //添加提成比例
                    $item['business_id'] = $result->id;
                    $businessCommissionRatioModel->create($item);
                }
            }

            Db::commit();
        }catch (ValidateException $e){
            Db::rollback();
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
        }
        $log->addOperate($request->param ('user_login_id'),message::$BUSINESS,message::$SUCC_SYSTEM_ADD_BUSINESS);

        return ReJson(message::$ERROR_CODE,message::$ERR_INSERT_DATA);
    }

    //删除业务
    public function delBusiness(Request $request, System $systemService,SystemOperateLog $log)
    {
        /**
         * @param $id
         */

        $id = $request->post('id');

        if (!isset($id)) ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

//        Log::error('测试日志信息，'.$id.'，并且实时写入');

        $result = $this->business->delBusinessModel($systemService->analysisId($id));

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_DATELE_DATA);
        }
        $log->addOperate($request->param ('user_login_id'),message::$BUSINESS,message::$SUCC_SYSTEM_DELETE_BUSINESS);

        return ReJson(message::$ERROR_CODE,message::$ERR_DATELE_DATA);

    }

    //修改业务
    public function editBusiness(Request $request,SystemOperateLog $log,SystemBusinessCommissionRatio $businessCommissionRatioModel)
    {
        /**
         * @param $id
         * @param $business_name
         * @param $business_type
         * @param $head_id string
         */
        $param = $request->post();

        Db::startTrans();
        try {

            Validate(Business::class)->scene('edit')->check($param);

            //是否有设置提成比列
            if (isset($param['commission_ratio']) & is_array ($param['commission_ratio'])){
                $commissionArr = $param['commission_ratio'];

                //先修改业务
                $result = $this->business->editBusinessModel($param);
                //先删除所有比例
                $businessCommissionRatioModel->delBidModel($param['id']);
                //提成比例入库
                foreach ($commissionArr as $item) {
                    //判断是否满足入库规则
//                    if (!$item['field'] || !$item['field2']){
//                        if ($item['field'] >= $item['field2']){
////                            $this->business->delBusinessModel (['id'=>$result->id]);
//                            return ReJson (message::$ERROR_CODE,message::$ERR_CHECK_COMMISSION_RATIO_BETWEEN);
//                        }
//                    }

                    //添加提成比例
                    $item['business_id'] = $result->id;
                    $businessCommissionRatioModel->create($item);
                }
            }
            Db::commit();
        }catch (ValidateException|\Exception $e){
            Db::rollback();
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE);
        }
        $log->addOperate($request->param ('user_login_id'),message::$BUSINESS,message::$SUCC_SYSTEM_UPDATE_BUSINESS);

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //启用 禁用业务
    public function isBusiness(Request $request,SystemOperateLog $log)
    {
        /**
         * @param $id
         * @param $is_k
         */
        $param = $request->post();

        try {

            Validate(Business::class)->scene('isDe')->check($param);

            $result = $this->business->editBusinessModel($param);

        }catch (ValidateException $e){
            ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE);
        }
        $log->addOperate($request->param ('user_login_id'),message::$BUSINESS,message::$SUCC_SYSTEM_BUSINESS_STATUS_DE);

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //业务搜索
    public function businessesSearch(Request $request)
    {
        $business_name = $request->get ('business_name');

        if (!isset($business_name)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $result = $this->business->getBusNameSearch($business_name);

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);

    }


    //归类业务列表
    public function getTypeTreeData(SystemBusiness $business,\app\service\Business $businessSer)
    {
        $busList = $business->getAllBusinessListModel();

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$businessSer->getBusClassify ($busList));
    }

}